package com.ylr.admin.framework.controller.web;

import java.util.List;
import java.util.Objects;

import com.ylr.admin.common.vo.role.user.RoleUserVo;
import com.ylr.admin.framework.service.RoleUserService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ylr.base.common.tool.Result;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2023-04-21 11:44:48
 * className: RoleUserWebController
 * version: 1.0
 * description:
 */
@RestController
@RequestMapping("/web/role-user")
@AllArgsConstructor
public class RoleUserWebController {

    private static final Logger log = LoggerFactory.getLogger(RoleUserWebController.class);

    private final RoleUserService roleUserService;

    /**
     * 保存角色关联用户接口
     * @param roleUserVo 参数对象
     */
    @RequestMapping("/saveOrUpdate")
    public Result<Object> saveOrUpdateRoleUser(@Validated @RequestBody RoleUserVo roleUserVo) {
        log.info("web => 开始保存角色关联用户操作。{}", roleUserVo);

        Long roleId = roleUserVo.getRoleIdList().get(0);
        List<Long> userIdList = roleUserVo.getUserIdList();
        if (Objects.isNull(roleId)) {
            log.info("角色主键值错误");
            return Result.requestFail("角色主键不能为空");
        }
        for (int i = 0; i < userIdList.size(); i++) {
            Long userId = userIdList.get(i);
            if (Objects.isNull(userId)) {
                log.info("用户主键值错误。i={}", i);
                return Result.requestFail("第" + (i +1) + "个用户主键不能为空");
            }
        }

        roleUserService.saveOrUpdateRoleUser(roleId, userIdList);

        log.info("web => 保存角色关联用户操作结束");
        return Result.success();
    }

    /**
     * 保存用户关联角色接口
     * @param roleUserVo 参数对象
     */
    @RequestMapping("/addOrModify")
    public Result<Object> addOrModifyRoleUser(@Validated @RequestBody RoleUserVo roleUserVo) {
        log.info("开始保存用户关联角色操作。{}", roleUserVo);

        List<Long> roleIdList = roleUserVo.getRoleIdList();
        Long userId = roleUserVo.getUserIdList().get(0);
        for (int i = 0; i < roleIdList.size(); i++) {
            Long roleId = roleIdList.get(i);
            if (Objects.isNull(roleId)) {
                log.info("角色主键值错误。i={}", i);
                return Result.requestFail("第" + (i +1) + "个角色主键不能为空");
            }
        }
        if (Objects.isNull(userId)) {
            log.info("用户主键值错误");
            return Result.requestFail("用户主键不能为空");
        }

        roleUserService.addOrModifyRoleUser(roleIdList, userId);

        log.info("保存用户关联角色操作结束");
        return Result.success();
    }

}
